package me.zhengjie.modules.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.domain.Api;
import me.zhengjie.modules.domain.ApiBatch;
import me.zhengjie.modules.domain.Batch;
import me.zhengjie.modules.domain.Companies;
import me.zhengjie.modules.domain.enterprise.*;
import me.zhengjie.modules.repository.ApiBatchMapper;
import me.zhengjie.modules.repository.ApiMapper;
import me.zhengjie.modules.repository.BatchMapper;
import me.zhengjie.modules.repository.CompaniesMapper;
import me.zhengjie.modules.repository.enterprise.*;
import me.zhengjie.modules.repository.intellectual.*;
import me.zhengjie.modules.service.EnterpriseInfService;
import me.zhengjie.modules.service.EnterpriseLegalService;
import me.zhengjie.modules.utils.Contents;
import me.zhengjie.modules.utils.DateUtils;
import me.zhengjie.modules.utils.JsonUtils;
import me.zhengjie.modules.utils.MyHttpUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("EnterpriseInfService")
@RequiredArgsConstructor
public class EnterpriseInfServiceImpl implements EnterpriseInfService {

    //公司信息
    private final CompaniesMapper companiesMapper;
    //企业基本信息
    private final EnterpriseInfMapper enterpriseInfMapper;

    //企业人员信息
    private final EnterprisePerMapper enterprisePerMapper;

    //企业行业信息
    private final EnterpriseIndMapper enterpriseIndMapper;

    //企业专利信息
    private final EnterIntPatentMapper enterIntPatentMapper;
    private final EnterIntSoftwareMapper enterIntSoftwareMapper;
    private final EnterIntTrademarkMapper enterIntTrademarkMapper;
    private final EnterIntWebSiteMapper enterIntWebSiteMapper;
    private final EnterpriseQuaMapper enterpriseQuaMapper;
    private final EnterIntWorksMapper enterIntWorksMapper;

    //企业投资信息
    private final EnterpriseInvMapper enterpriseInvMapper;
    private final EnterpriseFinMapper enterpriseFinMapper;

    private final EnterpriseLegalMapper enterpriseLegalMapper;
    private final EnterpriseAdmPenMapper enterpriseAdmPenMapper;

    private final ApiMapper apiMapper;
    private final BatchMapper batchMapper;
    private final ApiBatchMapper apiBatchMapper;

    /**
     * 解析map
     * 添加企业基本信息和员工信息
     * 员工信息绑定企业基本信息id
     * 如果有异常则回滚
     * @param map
     */
    @Transactional
    @Override
    public void addEnterpriseInformationByJson(Map<String, Object> map) {
        EnterpriseInformation e= (EnterpriseInformation) map.get("e");
        String category= (String) map.get("category");
        Long batchId=(Long) map.get("batchId");
        Long companiesId=(Long) map.get("companiesId");
        String enterpriseName= (String) map.get("enterpriseName");
        EnterpriseIndustry industry=null;
        EnterpriseIndustry ind=null;
        Long id=null;
        if(!category.equals("")&&category!=null){
            ind=enterpriseIndMapper.selectEnterpriseIndByName(category);
            if(ind!=null){
                id=ind.getId();
            }else{
                industry=new EnterpriseIndustry();
                industry.setCategory(category);
                industry.setCreateTime(new DateTime());
                industry.setDeleteFlag(false);
                industry.setBatchId(batchId);
                industry.setParentId(id);
                enterpriseIndMapper.insertEnterpriseIndReturnId(industry);
                id=industry.getId();
            }
            category= (String) map.get("categoryBig");
            if(!category.equals("")&&category!=null){
                ind=enterpriseIndMapper.selectEnterpriseIndByName(category);
                if(ind!=null){
                    id=ind.getId();
                }else{
                    industry=new EnterpriseIndustry();
                    industry.setCategory(category);
                    industry.setCreateTime(new DateTime());
                    industry.setDeleteFlag(false);
                    industry.setBatchId(batchId);
                    industry.setParentId(id);
                    enterpriseIndMapper.insertEnterpriseIndReturnId(industry);
                    id=industry.getId();
                }
                category= (String) map.get("categoryMiddle");
                if(!category.equals("")&&category!=null){
                    ind=enterpriseIndMapper.selectEnterpriseIndByName(category);
                    if(ind!=null){
                        id=ind.getId();
                    }else{
                        industry=new EnterpriseIndustry();
                        industry.setCategory(category);
                        industry.setCreateTime(new DateTime());
                        industry.setDeleteFlag(false);
                        industry.setBatchId(batchId);
                        industry.setParentId(id);
                        enterpriseIndMapper.insertEnterpriseIndReturnId(industry);
                        id=industry.getId();
                    }
                    category= (String) map.get("categorySmall");
                    if(!category.equals("")&&category!=null){
                        ind=enterpriseIndMapper.selectEnterpriseIndByName(category);
                        if(ind!=null){
                            id=ind.getId();
                        }else{
                            industry=new EnterpriseIndustry();
                            industry.setCategory(category);
                            industry.setCreateTime(new DateTime());
                            industry.setDeleteFlag(false);
                            industry.setBatchId(batchId);
                            industry.setParentId(id);
                            enterpriseIndMapper.insertEnterpriseIndReturnId(industry);
                            id=industry.getId();
                        }
                    }
                }
            }
        }
        e.setIndustryAll(id);
        e.setBatchId(batchId);
        e.setCompaniesId(companiesId);
        enterpriseInfMapper.insertEnterpriseInfReturnId(e);
        Long eId=e.getId();
        if(e.getEmployees().size()>0&&e.getEmployees()!=null){
            e.getEmployees().forEach(i->{
                Map<String, Object> m=JsonUtils.JsonToPerIntroduction(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/v4/open/description?name="+enterpriseName+"&cid="+i.getEyeId()));
                if(m!=null){
                    i.setIntroduction((String) m.get("introduction"));
                    i.setWeibo((String) m.get("weibo"));
                    i.setHeadUrl((String) m.get("headUrl"));
                }
                i.setEnterpriseId(eId);
                i.setBatchId(batchId);
                i.setCreateTime(new DateTime());
                i.setDeleteFlag(false);
            });
            enterprisePerMapper.insertPerByList(e.getEmployees());
        }
    }

    /**
     * 根据条件分页查询企业基本信息
     * @param map
     * @return
     */
    @Override
    public List<EnterpriseInformation> queryAllByPageForConditions(Map<String, Object> map) {
        return enterpriseInfMapper.selectAllByPageForConditions(map);
    }

    @Override
    public List<EnterpriseInformation> queryNewRound() {
        return enterpriseInfMapper.selectNewRound();
    }

    @Override
    public List<EnterpriseInformation> queryNewEnterpriseInf() {
        return enterpriseInfMapper.selectNewEnterpriseInf();
    }

    //@Scheduled(fixedDelay = 1000*24*60*60)
    @Transactional
    public void AutoCreateEnterpriseInf(){
        Api api=apiMapper.selectApiByVariableName("BASIC_ENTERPRISE_INF");
        ApiBatch apiBatches=apiBatchMapper.selectApiBatchByApiId(api.getId());
        if(apiBatches!=null){
            //apiBatches不为空，代表有数据，从数据库里拿数据去访问天眼查
            //获取云端数据
            Date now=new Date();
            long poor=now.getTime()-apiBatches.getCreateTime().getTime();
            long day= (long)api.getCycle()*24*60*60*1000;
            if(poor>day){
                //执行周期到了
                System.out.println("执行新一轮企业基本数据添加");
                List<Companies> companiesList=companiesMapper.selectAll();
                if(companiesList!=null&&companiesList.size()>0){
                    Long batchId=util.SnowFlakeUtil.getSnowFlakeId();
                    for (Companies c : companiesList) {
                        Map<String, Object> map= JsonUtils.JsonToEnterpriseInf(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/open/ic/baseinfoV3/2.0?keyword="+c.getCompanyName()+""));
                        if(map!=null){
                            map.put("batchId",batchId);
                            map.put("companiesId",c.getId());
                            map.put("enterpriseName",c.getCompanyName());
                            addEnterpriseInformationByJson(map);
                        }
                    }
                    Batch batch=new Batch();
                    batch.setCreateTime(new DateTime());
                    batch.setBatchNo(batchId);
                    batchMapper.insertBatch(batch);
                    ApiBatch apiBatch=new ApiBatch();
                    apiBatch.setApiId(api.getId());
                    apiBatch.setBatchId(batchId);
                    apiBatch.setCreateTime(new DateTime());
                    apiBatchMapper.insertApiBatch(apiBatch);
                }
            }else{
                //执行周期没到，直接结束方法运行
                System.out.println("执行周期未到");
                return;
            }
        }else{
            //为空 说明第一次执行，直接从天眼查获取数据
            System.out.println("企业基本---->目前暂无数据");
            List<Companies> companiesList=companiesMapper.selectAll();
            if(companiesList!=null&&companiesList.size()>0){
                Long batchId=util.SnowFlakeUtil.getSnowFlakeId();
                for (Companies c : companiesList) {
                    Map<String, Object> map= JsonUtils.JsonToEnterpriseInf(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/open/ic/baseinfoV3/2.0?keyword="+c.getCompanyName()+""));
                    if(map!=null){
                        map.put("batchId",batchId);
                        map.put("companiesId",c.getId());
                        map.put("enterpriseName",c.getCompanyName());
                        addEnterpriseInformationByJson(map);
                    }
                }
                Batch batch=new Batch();
                batch.setCreateTime(new DateTime());
                batch.setBatchNo(batchId);
                batchMapper.insertBatch(batch);
                ApiBatch apiBatch=new ApiBatch();
                apiBatch.setApiId(api.getId());
                apiBatch.setBatchId(batchId);
                apiBatch.setCreateTime(new DateTime());
                apiBatchMapper.insertApiBatch(apiBatch);
            }
        }
    }

    @Override
    public List<EnterpriseInformation> queryAll() {
        return enterpriseInfMapper.selectAll();
    }

    /**
     * 分页查询企业基本信息
     * @param map
     * @return
     */
    @Override
    public List<EnterpriseInformation> queryEnterpriseInfByPage(Map<String, Object> map) {
        return enterpriseInfMapper.selectEnterpriseInfByPage(map);
    }

    /**
     * 统计企业基本信息条数
     * @return
     */
    @Override
    public int queryEnterpriseInfByCount() {
        return enterpriseInfMapper.selectEnterpriseInfByCount();
    }

    @Override
    public EnterpriseInformation queryEnterpriseByName(String name) {
        return enterpriseInfMapper.selectEnterpriseByName(name);
    }

    @Override
    public EnterpriseInformation queryEnterpriseById(Integer id) {
        return enterpriseInfMapper.selectEnterpriseById(id);
    }

    @Override
    public List<EnterpriseInformation> queryEnterpriseInfoForPageByConditions(Map<String, Object> map) {
        return enterpriseInfMapper.selectEnterpriseInfoForPageByConditions(map);
    }

    @Override
    public int queryEnterpriseInfoForPageByConditionsToTotal(Map<String, Object> map) {
        return enterpriseInfMapper.selectEnterpriseInfoForPageByConditionsToTotal(map);
    }

    @Override
    public Map<String, Object> queryNumberInformation(String name) {
        Map<String,Object> map=new HashMap<>();
        int companiesCount=companiesMapper.selectCount();
        int patentTotal=enterIntPatentMapper.selectPatentByNameToTotal(name);
        float avgPatent=patentTotal/companiesCount;
        int softwareTotal=enterIntSoftwareMapper.selectSoftwareByNameToTotal(name);
        float avgSoftware=softwareTotal/companiesCount;
        int trademarkTotal=enterIntTrademarkMapper.selectTrademarkByNameToTotal(name);
        float avgTrademark=trademarkTotal/companiesCount;
        int websiteTotal=enterIntWebSiteMapper.selectWebsiteByNameTotal(name);
        int quaTotal=enterpriseQuaMapper.selectEnterpriseQuaByNameToTotal(name);
        float avgQua=quaTotal/companiesCount;
        int invTotal=enterpriseInvMapper.selectEnterpriseInvByNameToTotal(name);
        int legalTotal=enterpriseLegalMapper.selectEnterpriseLegalByNameToTotal(name);
        int admPenTotal=enterpriseAdmPenMapper.selectEnterpriseAdmPenByNameToTotal(name);
        map.put("patentTotal",patentTotal);
        map.put("softwareTotal",softwareTotal);
        map.put("trademarkTotal",trademarkTotal);
        map.put("websiteTotal",websiteTotal);
        map.put("quaTotal",quaTotal);
        map.put("invTotal",invTotal);
        map.put("legalTotal",legalTotal);
        map.put("admPenTotal",admPenTotal);
        map.put("avgPatent",avgPatent);
        map.put("avgSoftware",avgSoftware);
        map.put("avgTrademark",avgTrademark);
        map.put("avgQua",avgQua);
        return map;
    }

    @Override
    public List<String> queryEnterpriseInfForDistrict() {
        return enterpriseInfMapper.selectEnterpriseInfForDistrict();
    }

    @Override
    public List<Map<String,Object>> queryEnterpriseInfIndustryTopTen() {
        return enterpriseInfMapper.selectEnterpriseInfIndustryTopTen();
    }

    @Override
    public List<Map<String, Object>> queryEnterpriseInfMilestone(Long id,Date time) {
        List<String> timeList= DateUtils.getYear(time);
        Map<String, Object> map=new HashMap<>();
        map.put("id",id);
        List<Map<String, Object>> listMap=new ArrayList<>();
        Map<String, Object> dataMap=null;
        for (String s : timeList) {
            map.put("year",s);
            dataMap=new HashMap<>();
            dataMap.put("year",s);
            dataMap.put("patent",enterIntPatentMapper.selectPatentByIdAndYearForCount(map));
            dataMap.put("software",enterIntSoftwareMapper.selectSoftwareByIdAndYearForCount(map));
            dataMap.put("qua",enterpriseQuaMapper.selectEnterpriseQuaByIdAndYearForCount(map));
            dataMap.put("trademark",enterIntTrademarkMapper.selectTrademarkByIdAndYearForCount(map));
            dataMap.put("website",enterIntWebSiteMapper.selectWebsiteByIdAndYearForCount(map));
            dataMap.put("works",enterIntWorksMapper.selectWorksByIdAndYearForCount(map));
            dataMap.put("fin",enterpriseFinMapper.selectEnterpriseFinByIdAndYearForCount(map));
            dataMap.put("invest",enterpriseInvMapper.selectEnterpriseInvByIdAndYearForCount(map));
            dataMap.put("legal",enterpriseLegalMapper.selectEnterpriseLegalByIdAndYearForCount(map));
            dataMap.put("penalty",enterpriseAdmPenMapper.selectEnterpriseAdmPenByIdAndYearForCount(map));
            listMap.add(dataMap);
        }
        return listMap;
    }

    @Override
    public Map<String,Object> queryEnterpriseInfEvaluation(Long id){
        String year=DateUtils.getNewYear(1);
        Map<String, Object> map=new HashMap<>();
        map.put("id",id);
        Map<String, Object> dataMap=new HashMap<>();
        Integer paSum=0;
        Integer legSum=0;
        int patent=enterIntPatentMapper.selectPatentByIdAndYearForCount(map);
        paSum+=patent;
        int patTotal=enterIntPatentMapper.selectPatentByYearToTotal(year);
        dataMap.put("patent",patent);
        dataMap.put("patentAccounted",(patent/patTotal)+"%");
        int software=enterIntSoftwareMapper.selectSoftwareByIdAndYearForCount(map);
        paSum+=software;
        dataMap.put("software",software);
        int qua=enterpriseQuaMapper.selectEnterpriseQuaByIdAndYearForCount(map);
        paSum+=qua;
        int quaTotal=enterpriseQuaMapper.selectEnterpriseQuaByYearTotal(year);
        dataMap.put("qua",qua);
        dataMap.put("quaAccounted",(qua/quaTotal)+"%");
        int trademark=enterIntTrademarkMapper.selectTrademarkByIdAndYearForCount(map);
        paSum+=trademark;
        dataMap.put("trademark",trademark);
        int website=enterIntWebSiteMapper.selectWebsiteByIdAndYearForCount(map);
        paSum+=website;
        dataMap.put("website",website);
        int works=enterIntWorksMapper.selectWorksByIdAndYearForCount(map);
        paSum+=works;
        dataMap.put("works",works);
        dataMap.put("fin",enterpriseFinMapper.selectEnterpriseFinByIdAndYearForCount(map));
        dataMap.put("invest",enterpriseInvMapper.selectEnterpriseInvByIdAndYearForCount(map));
        int legal=enterpriseLegalMapper.selectEnterpriseLegalByIdAndYearForCount(map);
        legSum+=legal;
        dataMap.put("legal",legal);
        int penalty=enterpriseAdmPenMapper.selectEnterpriseAdmPenByIdAndYearForCount(map);
        legSum+=penalty;
        dataMap.put("penalty",penalty);
        dataMap.put("patSum",paSum);
        dataMap.put("legSum",legSum);
        return dataMap;
    }

    @Override
    public Map<String, Object> queryEnterpriseInfRankingByIndId(Long industryAll, Long companies_id) {
        Map<String, Object> map=new HashMap<>();
        List<EnterpriseInformation> list=enterpriseInfMapper.selectEnterpriseInfByIndId(industryAll);
        EnterpriseInformation information=null;
        int ranking=-1;
        for (int i = 0; i < list.size(); i++) {
             information=list.get(i);
             if(information.getCompaniesId()==companies_id){
                 ranking=i+1;
                 break;
             }
        }
        map.put("peerCount",list.size());
        map.put("ranking",ranking);
        return map;
    }
}
